<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <a-col flex="250px">
        <router-link to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/car.png" alt="logo" />
            <div class="title">车辆零部件缺陷检测</div>
          </div>
        </router-link>
      </a-col>
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { h, ref, type VNodeChild, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

interface MenuItem {
  key: string;
  icon?: () => VNodeChild;
  label: string;
  title: string;
}
interface MenuItemEvent {
  key: string;
}

const items = ref<MenuItem[]>([])

// 动态生成菜单
watch(
  () => router.getRoutes(),
  () => {
    const routes = router.getRoutes()
      .filter((route) => !route.meta?.hideInMenu)
      .sort((a, b) => {
        const orderA = Number(a.meta?.order ?? 999);
        const orderB = Number(b.meta?.order ?? 999);
        return orderA - orderB;
      });

    items.value = routes.map((route) => ({
      key: route.path,
      icon: () => h(route.meta?.icon),
      label: String(route.meta?.title),
      title: String(route.meta?.title)
    }));
  },
  { immediate: true }
);

// 当前高亮的菜单项
const current = ref<string[]>([])
router.afterEach((to) => {
  current.value = [to.path]
})

// 路由跳转事件
const doMenuClick = ({ key }: MenuItemEvent) => {
  router.push({
    path: key
  })
}
</script>

<style scoped>
#globalHeader .title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
